package com.android.porttallymansystem.ui.activity

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MenuItem
import androidx.recyclerview.widget.LinearLayoutManager
import com.android.porttallymansystem.R
import com.android.porttallymansystem.databinding.ActivityPersonMessageBinding
import com.android.porttallymansystem.logic.Repository
import com.android.porttallymansystem.logic.Setting
import com.android.porttallymansystem.logic.model.Message
import com.android.porttallymansystem.ui.adapter.MessageAdapter
import com.android.porttallymansystem.ui.adapter.PersonMessageAdapter
import kotlin.concurrent.thread

class PersonMessageActivity : AppCompatActivity() {

    private lateinit var binding: ActivityPersonMessageBinding

    private lateinit var messageList: ArrayList<Message>

    private lateinit var adapter: PersonMessageAdapter

    private var receiverId: Long? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityPersonMessageBinding.inflate(layoutInflater)
        setContentView(binding.root)
        setSupportActionBar(binding.toolbarPersonMessage)

        setStatusBar()

        initData()

        setListener()
    }

    private fun setListener() {
        binding.btSend.setOnClickListener {
            val content = binding.etInputText.text.toString()
            if (content.isNotEmpty()) {
                messageList.add(Message(content, Message.TYPE_SENT))
                adapter.notifyDataSetChanged()

                binding.rvPersonMessage.scrollToPosition(messageList.size - 1)
                binding.etInputText.setText("")

                thread {
                    Repository.sendMsg(content, receiverId!!)
                }
            }
        }
    }

    private fun initData() {
        thread {
            receiverId = intent.getLongExtra("person_id", 0)
            val receiver = Repository.getUser(receiverId!!)

            runOnUiThread {
                binding.tvToolbarTitle.text = receiver.name
            }

            messageList = Repository.getMessage(Setting.user.value!!.id, receiverId!!)
            adapter = PersonMessageAdapter(messageList)

            binding.rvPersonMessage.layoutManager = LinearLayoutManager(this)
            binding.rvPersonMessage.adapter = adapter
            adapter.notifyDataSetChanged()
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            android.R.id.home -> {
                finish()
                return true
            }
        }
        return super.onOptionsItemSelected(item)
    }

    private fun setStatusBar() {
//        window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
//                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
        window.statusBarColor = resources.getColor(R.color.green)
    }
}